package com.yt.app.h5.exception;

import com.alibaba.fastjson.JSON;
import com.yt.core.MsgBean;
import org.springframework.beans.TypeMismatchException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by dashan on 2017/11/21.
 */
public class AppExceptionHandler implements HandlerExceptionResolver {

    @ResponseBody
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception exception) {

        MsgBean msg = new MsgBean();
        if (exception instanceof TypeMismatchException) {
            TypeMismatchException typeEx = (TypeMismatchException) exception;
            msg.setFailure(1, String.format("参数值[%s]不是正确的类型", typeEx.getValue()));
        } else if (exception instanceof MissingServletRequestParameterException) {
            MissingServletRequestParameterException missingEx = (MissingServletRequestParameterException) exception;
            msg.setFailure(1, String.format("参数[%s]不可以为空", missingEx.getParameterName()));
        } else if (exception instanceof AppException) {
            msg.setFailure(((AppException) exception).getErrno(), ((AppException) exception).getErrdesc());
        } else {
            msg.setFailure(1, exception.getMessage());
            exception.printStackTrace();
        }
        try {
            response.setContentType("text/javascript; charset=utf-8");
            response.getWriter().write(JSON.toJSONString(msg.returnMsg()));
            response.flushBuffer();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return new ModelAndView();
    }
}
